import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpRequest } from "../../../../service/httpRequest";
import { NotiService } from "../../../../service/noti.service";
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { FileLoader } from "../../../../service/fileLoader";
import { PageModel } from "../../../../model/page-model";
import { GlobalVariable } from '../../../../global.config';

declare let $:any;
@Component({
  selector: 'app-single-monitor-united',
  templateUrl: './single-monitor-united.component.html',
  styleUrls: ['./single-monitor-united.component.css']
})
export class SingleMonitorUnitedComponent implements OnInit {
  loadDate:any;
  ofaulDate:any;
  faulttypeDate:any;
  powerDate:any;
  pressDate:any;
  aaData:any;
  propertyData:any;
  devinfoData:any;
  deviceId:string = '';
  chart1:any;
  chart2:any;
  chart3:any;
  private gizwitsNotiWs:any;
  private eventType = ['device.status.kv'];
  private tdata=[];
  private tmdata=[];
  pageModel = new PageModel();
  page:number = 1;
  tool = GlobalVariable.tooltip;

  constructor(private activeRoute:ActivatedRoute,private fileLoader:FileLoader,private noti:NotiService,private httpRequest:HttpRequest,private http:Http) { }

  ngOnInit() {
    this.fileLoader.LoadFileList(['assets/js/button.js'], function(){});
    this.activeRoute.params.subscribe(
      params=>{
        this.deviceId = params['deviceId'].replace('|','/');

        let p = this.deviceId.split('/');
        this.gizwitsNotiWs = this.noti.init(p[0].toLocaleLowerCase(),[p[1]],this.eventType,this.onEvent,this);
        this.gizwitsNotiWs.connect();
        this.initChart();
      }
    );

    this.getProperty();
    this.initDatePicker();   
    this.getFaultdata();
    this.initrealtimedata();
    this.getdevinfo();
    $("#mask").show();

  }

  change(i){
    let cboxs = $('.xx-box');
    if(i >= cboxs.length) return ;
    $.each(cboxs,function(j,n){
      $(n).hide();
      $('.nav-title').eq(j).removeClass('active')
    });
    $('.xx-box').eq(i).show();
    $('.nav-title').eq(i).addClass('active');
  }

  //设备信息的获取
  getdevinfo(){
    this.httpRequest.sendGet('devices',{id:this.deviceId}).subscribe(res => {  
      //console.log(res)    
      this.devinfoData = res.result;    
      console.log(this.devinfoData)  
    },err => console.log(err));
  }


 //故障数据
  getFaultdata(){
    this.httpRequest.sendGet('guzhang/page',{
      'page': this.page,
      'size': this.pageModel.itemsPerPage,
      'device_id':this.deviceId,
     
    }).subscribe(res => {      
      this.aaData = res.result.aaData;
      this.pageModel.setPage({'iTotalRecords':res.result.iTotalRecords});
    },err => console.log(err));
       
  }
//数据点数据
  getProperty(){    
    this.httpRequest.sendGet('product/property/list/'+this.deviceId.split('/')[0]).subscribe(res => {      
      this.propertyData = res.result[0];   
      console.log( this.propertyData)     
    },err => console.log(err));
  }
//实时获取
  initrealtimedata(){
    this.httpRequest.sendGet('common/realtime',{did:this.deviceId}).subscribe(res => {      
      //this.realtimeData = res; 
        $("#mask").hide(); 
        let dat = {Exhaustpress:'',Exhausttemp:'',Acurrent:''};
        //console.log(res)
        for(let i = 0;i<res.length;i++){                
            dat[res[i].property]=res[i].value
        }
        for(let i = 0;i<res.length;i++){                
            dat[res[i].property]=res[i].value
        }
        if(dat){
                //console.log(dat);
                let a = dat.Exhaustpress;
                this.updatechart(this.chart1,parseFloat(a));
            
                let b = dat.Exhausttemp;
                this.updatechart(this.chart2,parseFloat(b));
           
                let c = dat.Acurrent;
                this.updatechart(this.chart3,parseFloat(c));
            for(let key in dat){                    
                $("#"+key).text(dat[key]);                
                if(key=="Loadruntime"){
                    $("#Loadruntime1").text(dat[key])
                }          
                if(key=="Runtime"){
                    $("#Runtime1").text(dat[key])
                }    
                if(key=="Srun" && dat[key]=="0"){
                    $("#Srun").text('停止');
                    $("#Srun1").removeClass("blue");
                    $("#Srun1").addClass("red");
        
                }
                if(key=="EnvHumidity"){
                    $("#EnvHumidity").text(dat[key]+"%")
                }
                if(key=="Srun" && dat[key]=="1"){
                    $("#Srun").text('运行');
                    $("#Srun1").removeClass("red");
                    $("#Srun1").addClass("blue");                      
                }
             
                if(key=="Sload" && dat[key]=="0"){              
                    $("#Sload").text('卸载');
                    $("#Sload1").removeClass("blue");
                    $("#Sload1").addClass("red");
        
               }
               if(key=="Sload" && dat[key]=="1"){              
                    $("#Sload").text('加载');
                    $("#Sload1").removeClass("red");
                    $("#Sload1").addClass("blue");
        
               }
               
                 if(key == "Flongstop" && dat[key]=="1"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("gray");
                    $("#"+key).addClass("red");
                 }
                 if(key == "Flongstop" && dat[key]=="0"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("red");
                    $("#"+key).addClass("gray");
                 }
                if(key == "Ffault" && dat[key]=="1"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("gray");
                    $("#"+key).addClass("red");
                 }
                 if(key == "Ffault" && dat[key]=="0"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("red");
                    $("#"+key).addClass("gray");
                 }
                   if(key == "Fwarn" && dat[key]=="1"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("gray");
                    $("#"+key).addClass("red");
                 }
                 if(key == "Fwarn" && dat[key]=="0"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("red");
                    $("#"+key).addClass("gray");
                 }
                 if(dat[key]=="0" && $("#"+key).attr("ftag")=="fault"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("red-box");
                    $("#"+key).addClass("gray-box");
                 }
                 if(dat[key]=="1" && $("#"+key).attr("ftag")=="fault"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("gray-box");
                    $("#"+key).addClass("red-box");
                 }
                 if(dat[key]=="0" && $("#"+key).attr("stag")=="spara"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("orange-box");
                    $("#"+key).addClass("gray-box");
                 }
                 if(dat[key]=="1" && $("#"+key).attr("stag")=="spara"){
                    $("#"+key).text("");
                    $("#"+key).removeClass("gray-box");
                    $("#"+key).addClass("orange-box");
                 }  
            }
        }            

              
    },err => console.log(err));         
            
            
  }
  //时间插件的初始化
  initDatePicker(){
    $(".form_datetime").datetimepicker({
            format: "yyyy-mm-dd hh:ii",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 30 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date()  
      });
      $(".form_datetime1").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),        
            minView:1

      });
      $(".form_datetime2").datetimepicker({
            format: "yyyy-mm-dd hh:00",        
            todayBtn:  1,    
            startDate : new Date(new Date().getTime() - 365 * 24 * 3600 * 1000),
            autoclose : true,  
            todayHighlight : true,  
            initialDate : new Date(),  
            endDate : new Date(),
            minView:1  
        });


    $('#qBeginTime').datetimepicker().on('changeDate',function(e){  
        var startTime = e.date;  
        $('#qEndTime').datetimepicker('setStartDate',startTime);  

    });  
      
    $('#qEndTime').datetimepicker().on('changeDate',function(e){  
        var endTime = e.date;  
        $('#qBeginTime').datetimepicker('setEndDate',endTime);  
    });

  }

//查询历史数据
   public count = 0;   
   public selectedproperty:any = {};
   fn($event,property){  
     let checkbox = $event.target; 
        if (checkbox.checked) {
            this.count++;
            this.selectedproperty[property]=property;
        }else{
            this.count--;
            delete this.selectedproperty[property];
        }                
      if(this.count>5){
        alert("对不起，每次展示参数最多可以选择5个！");
        checkbox.checked = false;
        this.count=5;
      }             
    }         


    chosedparam(){       
      let properties = [];
      let btn = $("#myButton").button('loading') 
      for(let key in this.selectedproperty){
        properties.push(key)
      }
      let str = properties.join(',')
      let sdate = $('#stime').val(); 
      //console.log(sdate) 
       //console.log(str) 
      if(str!=''&&sdate!=''){
          let headers = new Headers();
          let authToken = localStorage.getItem("token");
          headers.append('Authorization', `token ${authToken}`);
          let options = new RequestOptions({ headers: headers }); 
          this.http.post('http://101.37.24.73:8088/gh30',{
            device_id:this.deviceId,
            sdate:sdate,
            parameter:str
          },options).subscribe(res=>{
            //console.log(res.json())            
            btn.button('reset');       
            let gh30data = res.json().result.aaData;
            console.log(gh30data)
            this.tdata = res.json().result.aaData;
            this.getqxdata('getqx',gh30data);
          },err=>{
            alert('查询失败');
            btn.button('reset'); 
          })    
          
      }else{
        alert('请选择参数或者时间');
        btn.button('reset'); 
      }
      // setTimeout(function () { },1000); 
     
  
    }  

    chosedparam1(){
      let btn1 = $("#myButton1").button('loading') 
      let properties = [];      
      for(let key in this.selectedproperty){
        properties.push(key)
      }
      let str = properties.join(',')
      let sdate = $('#qBeginTime').val();
      let edate = $('#qEndTime').val();
      //console.log(sdate) 
       //console.log(str) 
      if(str!=''&&sdate!=''&&edate!=''){
          let headers = new Headers();
          let authToken = localStorage.getItem("token");
          headers.append('Authorization', `token ${authToken}`);
          let options = new RequestOptions({ headers: headers }); 
          this.http.post('http://101.37.24.73:8088/gh',{
            device_id:this.deviceId,
            sdate:sdate,   
            edate:edate,              
            parameter:str
          },options).subscribe(res=>{
            //console.log(res.json())
            btn1.button('reset');             
            let ghdata = res.json().result.aaData;
            this.tmdata = res.json().result.aaData;
            this.getqxdata('getqx1',ghdata);

          },err=>{
            alert('查询失败');
            btn1.button('reset'); 
          })    
          
      }else{
        alert('请选择参数或者时间');
        btn1.button('reset'); 
      } 
   

     
}

getqxdata(id,data){
  $('#'+id).highcharts({
    chart: {
        type: 'spline'
    },
    title: {
        text: '参数的历史数据曲线'
    },
    
    xAxis: {
        type: 'datetime',
        labels: {
            overflow: 'justify'
        }
    },
    yAxis: {
        title: {
            text: '参数值'
        },
        minorGridLineWidth: 0,
        gridLineWidth: 0,
        alternateGridColor: null,
    
    },
    tooltip: {
        valueSuffix: ''
    },
    plotOptions: {
        spline: {
            lineWidth: 2,
            states: {
                hover: {
                    lineWidth: 3
                }
            },
            marker: {
                enabled: false
            },
            pointInterval: 3600000, // one hour
            // pointStart: Date.UTC(2015, 4, 31, 0, 0, 0)
        }
    },
    series: data,
    navigation: {
        menuItemStyle: {
            fontSize: '10px'
        }
    }
});
}



//仪表盘的初始化
  initChart(){
    let plotBands = [
      {from: 0, to: 5, color: '#55BF3B' },
      { from: 5,to: 10,color: '#DDDF0D'},
      {from: 10,to: 16,color: '#DF5353'}];
    this.init('angular-gauge1','排气压力',-150,150,0,16,'压力',0.0,'Bar',plotBands,(chart) =>{
      this.chart1 = chart;
    });

    plotBands = [
      {from: 0, to: 120, color: '#55BF3B' },
      { from: 120,to:160 ,color: '#DDDF0D'},
      {from: 160,to: 200,color: '#DF5353'}];
    this.init('angular-gauge2','排气温度',-150,150,0,200,'温度',0.0,'℃',plotBands,(chart) =>{
      this.chart2 = chart;
    });

    plotBands = [
      {from: 0, to: 350, color: '#55BF3B' },
      { from: 350,to: 700,color: '#DDDF0D'},
      {from: 700,to:1000,color: '#DF5353'}];
    this.init('angular-gauge3','主机A项电流',-150,150,0,1000,'电流',0.0,'A',plotBands,(chart) =>{
      this.chart3 = chart;
    });
  }

//websocket获取
  onEvent(msgs,that){
    $("#mask").hide(); 
    let did = msgs.did;
    let msg = msgs.data;
    let a = msg.Exhaustpress.toFixed(1);
    that.updatechart(that.chart1,parseFloat(a));

    let b = msg.Exhausttemp.toFixed(1);
    that.updatechart(that.chart2,parseFloat(b));

    let c = msg.Acurrent.toFixed(1);
    that.updatechart(that.chart3,parseFloat(c));

    for(let key in msg){
      $("#"+key).text(msg[key].toFixed(1));
      if(key=="Loadruntime"){
        $("#Loadruntime1").text(msg[key])
      }
      if(key=="Runtime"){
        $("#Runtime1").text(msg[key])
      }
      if(key=="Srun" && msg[key]=="0"){
        $("#Srun").text('停止');
        $("#Srun1").removeClass("blue");
        $("#Srun1").addClass("red");

      }
      if(key=="EnvHumidity"){
        $("#EnvHumidity").text(msg[key]+"%")
      }
      if(key=="Srun" && msg[key]=="1"){
        $("#Srun").text('运行');
        $("#Srun1").removeClass("red");
        $("#Srun1").addClass("blue");
      }
      a = msg.Srun;
      if(key=="Sload" && msg[key]=="0"){
        $("#Sload").text('卸载');
        $("#Sload1").removeClass("blue");
        $("#Sload1").addClass("red");

      }
      if(key=="Sload" && msg[key]=="1"){
        $("#Sload").text('加载');
        $("#Sload1").removeClass("red");
        $("#Sload1").addClass("blue");

      }

      if(key == "Flongstop" && msg[key]=="1"){
        $("#"+key).text("");
        $("#"+key).removeClass("gray");
        $("#"+key).addClass("red");
      }
      if(key == "Flongstop" && msg[key]=="0"){
        $("#"+key).text("");
        $("#"+key).removeClass("red");
        $("#"+key).addClass("gray");
      }
      if(key == "Ffault" && msg[key]=="1"){
        $("#"+key).text("");
        $("#"+key).removeClass("gray");
        $("#"+key).addClass("red");
      }
      if(key == "Ffault" && msg[key]=="0"){
        $("#"+key).text("");
        $("#"+key).removeClass("red");
        $("#"+key).addClass("gray");
      }
      if(key == "Fwarn" && msg[key]=="1"){
        $("#"+key).text("");
        $("#"+key).removeClass("gray");
        $("#"+key).addClass("red");
      }
      if(key == "Fwarn" && msg[key]=="0"){
        $("#"+key).text("");
        $("#"+key).removeClass("red");
        $("#"+key).addClass("gray");
      }
      if(msg[key]=="0" && $("#"+key).attr("ftag")=="fault"){
        $("#"+key).text("");
        $("#"+key).removeClass("red-box");
        $("#"+key).addClass("gray-box");
      }
      if(msg[key]=="1" && $("#"+key).attr("ftag")=="fault"){
        $("#"+key).text("");
        $("#"+key).removeClass("gray-box");
        $("#"+key).addClass("red-box");
      }
      if(msg[key]=="0" && $("#"+key).attr("stag")=="spara"){
        $("#"+key).text("");
        $("#"+key).removeClass("orange-box");
        $("#"+key).addClass("gray-box");
      }
      if(msg[key]=="1" && $("#"+key).attr("stag")=="spara"){
        $("#"+key).text("");
        $("#"+key).removeClass("gray-box");
        $("#"+key).addClass("orange-box");
      }
    }

  }

  updatechart(chart,data){
    if (!chart.renderer.forExport) {
      let point = chart.series[0].points[0];
      point.update(data);
    }
  }

  init(id,text,startAg,endAg,min,max,name,initVal,subfix,pb,cb){
    $('#' + id).highcharts({

        chart: {
          type: 'gauge',
          plotBackgroundColor: null,
          plotBackgroundImage: null,
          plotBorderWidth: 0,
          plotShadow: false
        },
        title:{
          text: ''

        },
        pane: {
          startAngle: startAg,
          endAngle: endAg,
          background: [{
            backgroundColor: {
              linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
              stops: [
                [0, '#FFF'],
                [1, '#333']
              ]
            },
            borderWidth: 0,
            outerRadius: '109%'
          }, {
            backgroundColor: {
              linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
              stops: [
                [0, '#333'],
                [1, '#FFF']
              ]
            },
            borderWidth: 1,
            outerRadius: '107%'
          }, {

          }, {
            backgroundColor: '#DDD',
            borderWidth: 0,
            outerRadius: '105%',
            innerRadius: '103%'
          }]
        },

        yAxis: {
          min: min,
          max: max,
          minorTickInterval: 'auto',
          minorTickWidth: 1,
          minorTickLength: 10,
          minorTickPosition: 'inside',
          minorTickColor: '#666',
          tickPixelInterval: 30,
          tickWidth: 2,
          tickPosition: 'inside',
          tickLength: 10,
          tickColor: '#666',
          labels: {
            step: 2,
            rotation: 'auto'
          },
          title: {
            text: subfix
          },
          plotBands: pb
        },

        series: [{
          name: name,
          data: [initVal],
          tooltip: {
            valueSuffix: ' '+ subfix +' '
          }
        }]

      },
      function (chart) {
        cb(chart);
      });
  }

}
